<template>
  <div class="schema-node" :style="{ marginLeft: depth * 3 + 'px' }">
    <div class="flex-justify-start">
      <div class="toggle-button">
        <el-button
          v-if="canAddChild"
          @click="isExpanded = !isExpanded"
          type="text"
          size="mini"
        >
          <i :class="isExpanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
        </el-button>
      </div>
      <div class="node-header">
        <!-- 展开/折叠按钮 -->
        <el-input v-model="localNode.filed" placeholder="字段名" size="mini"
                  :disabled="localNode.isRoot || localNode.isArrayItem"/>
        <el-select v-model="localNode.type" @change="handleTypeChange" size="mini">
          <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>

        <el-input v-model="localNode.xMock" placeholder="Mock" size="mini" :disabled="localNode.isRoot || canAddChild"/>
        <el-input v-model="localNode.title" placeholder="中文名" size="mini" :disabled="localNode.isArrayItem"/>
        <el-input v-model="localNode.description" placeholder="说明" size="mini"/>
        <el-checkbox v-model="localNode.isRequired" size="mini"  :disabled="localNode.isRoot || localNode.isArrayItem"/>
        <div class="node-actions">
          <el-button v-if="localNode.type==='object'" @click="addChild" size="mini" type="text">+子节点</el-button>
          <el-popover
            placement="top"
            width="400"
            trigger="click">
            <JsonSchemaSetting :schema="localNode"></JsonSchemaSetting>
            <el-button size="mini" type="text" icon="el-icon-setting" slot="reference"/>
          </el-popover>
          <el-button @click="removeNode" class="font-color-danger" size="mini" type="text" icon="el-icon-delete"
                     v-show="!localNode.isRoot"/>
        </div>
      </div>
    </div>
    <!-- 子节点容器 -->
    <div v-if="canAddChild" class="node-children" v-show="isExpanded">
      <template v-if="hasChildren">
        <schema-node
          v-for="child in localNode.children"
          :key="child.id"
          :node="child"
          :depth="depth + 1"
          @update="handleChildUpdate"
          @delete="$emit('delete', $event)"
        />
      </template>
    </div>

  </div>
</template>

<script>
  import {generateUID} from "@/utils";
  import JsonSchemaSetting from "@/page/assetManagement/partial/JsonSchemaSetting.vue";

  export default {
    name: 'SchemaNode',
    components: {
      JsonSchemaSetting
    },
    props: {
      node: {
        type: Object,
        default: () => ({})
      },
      depth: {
        type: Number,
        default: 0
      },
    },
    data() {
      return {
        localNode: {},
        isExpanded: true, // 默认展开状态
        types: [
          {label: 'String', value: 'string'},
          {label: 'Number', value: 'number'},
          {label: 'integer', value: 'integer'},
          {label: 'Boolean', value: 'boolean'},
          {label: 'Array', value: 'array'},
          {label: 'Object', value: 'object'},
          {label: 'null', value: 'null'}
        ],
        // 新增标记用于识别更新来源
        isExternalUpdate: false
      }
    },
    computed: {
      canAddChild() {
        return ['array', 'object'].includes(this.localNode.type)
      },
      hasChildren() {
        return this.localNode.children?.length > 0
      },
    },
    watch: {
      node: {
        deep: true,
        immediate: true,
        handler(newVal) {
          // 标记为外部更新
          this.isExternalUpdate = true;
          this.localNode = JSON.parse(JSON.stringify(newVal))
          this.$nextTick(() => {
            this.isExternalUpdate = false;
          });
        }
      },
      localNode: {
        deep: true,
        immediate: true,
        handler(newVal) {
          if (!this.isExternalUpdate) {
            this.$emit('update', newVal);
          }
        }
      }
    },
    methods: {
      addChild() {
        if (!this.localNode.children) this.localNode.children = []
        this.localNode.children.push({
          id: generateUID(),
          filed: '',
          type: 'string',
          title: '',
          xMock: '',
          description: '',
          isRequired: false,
          children: []
        })
      },
      removeNode() {
        this.$emit('delete', this.localNode.id)
      },
      handleChildUpdate(updatedNode) {
        const index = this.localNode.children.findIndex(n => n.id === updatedNode.id)
        if (index > -1) {
          this.$set(this.localNode.children, index, updatedNode)
        }
      },
      handleTypeChange(val) {
        this.localNode.children = []
        if (val === 'array') {
          console.log(555, this.localNode)
          if (!this.localNode.isRoot) {
            // this.localNode.filed = 'Items'
            // this.localNode.isArrayItem = true
            this.localNode.children.push({
              id: generateUID(),
              filed: 'items',
              type: 'string',
              xMock: '',
              isArrayItem: true,
              isRequired: false,
              children: []
            })
          } else {
            this.localNode.children.push({
              id: generateUID(),
              filed: 'items',
              type: 'string',
              xMock: '',
              isArrayItem: true,
              isRequired: false,
              children: []
            })
          }

        }
      }
    }
  }
</script>

<style scoped>
  .schema-node {
    margin: 2px 0;
    padding: 3px;
    border: 0 solid #ebeef5;
    border-radius: 4px;
    transition: all 0.3s;
  }

  .node-header {
    display: grid;
    grid-template-columns: 100px 100px 100px 100px 100px 20px auto;
    gap: 10px;
    align-items: center;
  }

  .toggle-button {
    padding: 0;
    margin-right: 5px;
    width: 15px;

  }

  .node-actions {
    display: flex;
    gap: 5px;
    margin-left: 10px;
  }

  .node-children {
    margin-top: 10px;
    border-left: 0 dashed #e4e7ed;
    padding-left: 10px;
  }

  .empty-children {
    color: #909399;
    font-size: 12px;
    padding: 8px;
    margin-top: 5px;
  }
</style>
